package com.ptjob.basecore.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {
    private static Context mContext;

    public static void initialise(Context context) {
        mContext = context;
        NetWorkTypeUtils.initialise(context);
    }

    /**
     * appdeviceid:deviceid+macaddress
     *
     * @param context
     * @return
     */
    @Deprecated public static String getAppDeviceId(Context context) {

        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
                Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getDeviceId();

        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        if (wifiInfo != null) {
            String macAddress = wifiInfo.getMacAddress();
            deviceId = deviceId + macAddress;
        }

        if (deviceId == null || "".equals(deviceId.trim())) {
            deviceId = "-";
        }

        return MD5Helper(deviceId);
    }

    public static String MD5Helper(String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
            byte[] byteArray = messageDigest.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    sb.append("0")
                            .append(Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    sb.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("no device Id");
    }

    //获取rom厂商
    public static String getRomFacturer() {

        return "" + Build.MANUFACTURER;
    }

    /**
     * 获取客户端版本号
     *
     * @param context
     * @return
     */
    public static int getClientVersionCode(Context context) {
        if (context == null) {
            return 0;
        }
        try {
            PackageInfo packInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取osversionname
     */
    public static String getOSVersionName() {
        return Build.VERSION.RELEASE;
    }

    public static int getOSVersionCode() {
        int version = -1;
        try {
            version = Integer.valueOf(Build.VERSION.SDK_INT);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 获取厂商品牌
     */
    public static String getBrandName() {
        String brand = Build.BRAND;
        if (brand == null || brand.length() <= 0) {
            return "";
        } else {
            return getData(brand);
        }
    }

    /**
     * 获取modelname
     *
     * @return
     */
    public static String getModelName() {
        String model = Build.MODEL;
        if (model == null || model.length() <= 0) {
            return "";
        } else {
            return getData(model);
        }
    }

    public static String getData(String data) {
        if (data == null || data.length() <= 0) {
            return "-";
        } else {
            return data.replace(" ", "_");
        }
    }

    /**
     * 获取cpu核数
     */
    public static int getNumCores() {
        // Private Class to display only CPU devices in the directory listing
        class CpuFilter implements FileFilter {
            @Override public boolean accept(File pathname) {
                // Check if filename is "cpu", followed by a single digit number
                if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                    return true;
                }
                return false;
            }
        }

        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            // Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            // Default to return 1 core
            return 1;
        }
    }

    /**
     * 时间转换时：分：秒
     */
    public static String stringForTime(long timeMs) {

        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());

        try {
            int totalSeconds = (int) (timeMs / 1000);

            int seconds = totalSeconds % 60;
            int minutes = (totalSeconds / 60) % 60;
            int hours = totalSeconds / 3600;

            formatBuilder.setLength(0);

            return formatter.format("%02d:%02d:%02d", hours, minutes, seconds)
                    .toString();
        } finally {
            formatter.close();
        }
    }

    /**
     * 时间转换分：秒
     */
    public static String stringForTimeNoHour(long timeMs) {

        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());

        try {
            int totalSeconds = (int) (timeMs / 1000);

            int seconds = totalSeconds % 60;
            int minutes = totalSeconds / 60;

            formatBuilder.setLength(0);

            return formatter.format("%02d:%02d", minutes, seconds).toString();
        } finally {
            formatter.close();
        }
    }

    public static long getTimeLong(String date) {
        SimpleDateFormat format = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm");// ���ø�ʽ

        Date mDate;
        try {
            mDate = format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            mDate = new Date();
        }

        return mDate.getTime();
    }

    /**
     * 判断网络是否可用
     */
    public static boolean isNetAvailableForPlay(final Context context) {

        NetworkInfo networkInfo = null;
        try {
            networkInfo = NetWorkTypeUtils.getAvailableNetWorkInfo();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (networkInfo == null) {
            return false;
        }

        return true;
    }

    /**
     * 验证邮箱格式是否正确
     *
     * @param email
     * @return
     */
    public static boolean emailFormats(String email) {
        if (email == null)
            return false;
        String regular = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher = pattern.matcher(email);
        if (!matcher.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 校验验证码是数字或者字母
     */
    public static boolean verFormat(String ver) {
        if (ver == null)
            return false;
        String regular = "^[a-zA-Z0-9_]{4}$";
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher = pattern.matcher(ver);
        if (!matcher.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 验证密码是否是 数字和字母，英文符号 长度6-16,区分大小写
     */
    public static boolean passwordFormat(String password) {
        if (password == null)
            return false;

        String regular = "^[a-zA-Z0-9!`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]{6,16}$";
        //String regular = "^[,\\.;\\:\"\'!a-zA-Z0-9_]{6,16}$";
        //String regular = "/^[\w.]{6,16}$/";
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher = pattern.matcher(password);
        if (!matcher.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 验证注册手机号码是否正确
     */
    public static boolean isMobileNO(String mobiles) {
        if (mobiles == null) {
            return false;
        }
        Pattern p = Pattern.compile("^(1)\\d{10}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断sdcard是否存在
     *
     * @return
     */
    public static boolean sdCardMounted() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED) && !state
                .equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return true;
        }
        return false;
    }

    /**
     * 获取分辨率
     *
     * @param context
     * @return
     */
    public static String getResolution(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return new StringBuilder().append(dm.widthPixels).append("*")
                .append(dm.heightPixels).toString();
    }

    /**
     * 获取密度
     *
     * @param context
     * @return
     */
    public static String getDensity(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return String.valueOf(dm.density);
    }

    /**
     * 获取imei号
     *
     * @return
     */
    public static String getIMEI(Context context) {
        try {
            String deviceId = ((TelephonyManager) context.getSystemService(
                    Context.TELEPHONY_SERVICE))
                    .getDeviceId();
            if (null == deviceId || deviceId.length() <= 0) {
                return "";
            } else {
                return deviceId.replace(" ", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}
